package message_api

import (
	"gin_study_blog/common"
	"gin_study_blog/common/http"
	"gin_study_blog/models"
	"gin_study_blog/utils"
	"github.com/gin-gonic/gin"
)

type MessageRequest struct {
	SendUserID uint   `json:"send_user_id" binding:"required" msg:"请选择发送人"` // 发送人
	RevUserID  uint   `json:"rev_user_id" binding:"required" msg:"请选择接收人"`  // 接收人
	Content    string `json:"content"`                                      // 消息内容
}

// MessageCreateView 发布消息
func (MessageApi) MessageCreateView(c *gin.Context) {
	var cr MessageRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		http.FailWithError(err, &cr, c)
		return
	}
	claims, _ := c.Get("user")
	user := claims.(*utils.UserClaims)
	var sendUser, RevUser models.UserModel
	err = common.DB.Take(&sendUser, "id = ?", user.UserID).Error
	if err != nil {
		http.FailWithMessage("发送人不存在", c)
		return
	}

	err = common.DB.Take(&RevUser, cr.RevUserID).Error
	if err != nil {
		http.FailWithMessage("接收人不存在", c)
		return
	}

	err = common.DB.Create(&models.MessageModel{
		SendUserID:       sendUser.ID,
		SendUserNickName: sendUser.NickName,
		SendUserAvatar:   sendUser.Avatar,
		RevUserID:        RevUser.ID,
		RevUserNickName:  RevUser.NickName,
		RevUserAvatar:    RevUser.Avatar,
		IsRead:           false,
		Content:          cr.Content,
	}).Error
	if err != nil {
		http.FailWithMessage("信息发送失败", c)
		return
	}
	http.IsOkWithMessage("消息发送成功", c)
}
